# from PyQt5.QtWidgets import QApplication
# import sys
import time

import cv2
import numpy as np
import win32con
import win32gui
import win32ui
from redis import Redis

hwnd_id = []

redis = Redis(host='localhost', port=6379, db=1)


def get_all_hwnd(hwnd, mouse):
    if (win32gui.IsWindow(hwnd) and
        win32gui.IsWindowEnabled(hwnd) and
        win32gui.IsWindowVisible(hwnd)) and win32gui.GetWindowText(hwnd).__contains__('Hollow Knight'):
        hwnd_id.append(hwnd)


win32gui.EnumWindows(get_all_hwnd, 0)

handle = hwnd_id[0]

print(handle)

# 激活窗口
win32gui.SetForegroundWindow(handle)

# 将窗口移动到左上角
win32gui.MoveWindow(handle, -10, -31, 1280, 720, True)

# time.sleep(2)
# 截图
# 创建dc, 截取桌面
hdesktop = win32gui.GetDesktopWindow()
# 获取窗口大小
l, t, r, b = win32gui.GetWindowRect(handle)
width = r - l
height = b - t
# width = 1280
# height = 720
# 创建设备描述表
desktop_dc = win32gui.GetWindowDC(hdesktop)
# 创建dc对象
mfc_dc = win32ui.CreateDCFromHandle(desktop_dc)
# 创建内存设备描述表
save_dc = mfc_dc.CreateCompatibleDC()
# 创建位图对象
save_bit_map = win32ui.CreateBitmap()
# 截图 从左上角100,100开始截图，截图大小为width-200, height-200
save_bit_map.CreateCompatibleBitmap(mfc_dc, width, height)
start = time.time()
save_dc.SelectObject(save_bit_map)
# 截取从左上角(100, 100)长宽为(width, height)的图片
# save_dc.BitBlt((0, 0), (width - 20, height - 40), mfc_dc, (0, 0), win32con.SRCCOPY)
save_dc.BitBlt((0, 0), (width - 300, height - 160), mfc_dc, (150, 50), win32con.SRCCOPY)

# 保存位图文件
signedIntsArray = save_bit_map.GetBitmapBits(True)
img = np.frombuffer(signedIntsArray, dtype='uint8')
img.shape = (height, width, 4)
# 删除超出部分
img = img[0:height - 160, 0:width - 300]
# 缩放至 5分之一
img = cv2.resize(img, (175, 175))
# 保存
cv2.imwrite('test.png', img)
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(gray.shape)
# 缩放至二十分之一
# gray = cv2.resize(gray, (int(width / 5), int(height / 5)))
# 保存
cv2.imwrite('test_gray.png', gray)
# 二值化
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 转成numpy数组
binary = np.array(binary)
# 保存
cv2.imwrite('test_binary.png', binary)
binary_2 = binary / 255
# 刷新app, 避免截取到上一次的图片
print(time.time() - start)
while True:
    start = time.time()
    # redis.set("can_action", "1")
    # redis.set("can_action", "0")
    print(str(redis.get('done').decode('utf-8')))
    state = redis.brpop(['start'])
    print(state)
    print('one')
    end = time.time()
    # time.sleep(10)
    print(end - start)
